<?php


namespace App\Http\Controllers\Estate;


use App\Http\Controllers\Controller;
use App\Models\ElementModel;
use App\Models\FloorModel;
use App\Models\HomeBanner;
use App\Models\HouseModel;
use App\Services\ElementService;
use App\Services\HouseService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class ElementController extends Controller
{
    public $service;

    public function __construct()
    {
        $this->service = new ElementService();
    }

    /**
     * 列表
     * @param Request $request
     * @return array
     */
    public function index(Request $request)
    {
        $user  = $request->user();
        $param = $request->query();
        //查询当前物业自己添加的数据
        $where['estate_id'] = $user['estate_id'];
        return $this->success($this->service->getElementList($where, $param));
    }

    /**
     * 新增
     * @param Request $request
     * @return array
     */
    public function store(Request $request)
    {
        $user = $request->user();
        $data = $request->post();
        $result = $this->service->addElement($data,$user['estate_id']);
        if ($result === false) {
            return $this->error($this->service->getMessage());
        }

        return $this->success('添加成功');

    }

    /**
     * 获取详情
     * @param $id
     * @return array
     */
    public function show(HouseService $houseService,$f_id)
    {
        $info = FloorModel::with('element:e_id,element_num')->where('f_id', $f_id)->first();
        $house_list = $houseService->getHouseListByCommunity($info->c_id);
        return $this->success(['list' => $info, 'house_list' => $house_list]);
    }

    /**
     * 编辑
     * @param Request $request
     * @return array
     */
    public function update(Request $request, $id)
    {
        $data                 = $request->post();
        $info = FloorModel::find($id);
        if (!$info) {
            return $this->error('该数据不存在');
        }
        $info->floor = $data['floor'];
        try {
            $info->save();
        } catch (\Throwable $e) {
            return $this->error('该楼层已存在，不可重复添加');
        }
        return $info->save() ? $this->success('修改成功!') : $this->error('修改失败!');
    }

    /**
     * 删除
     * @param Request $request
     * @return array
     */
    public function destroy(FloorModel $floorModel, $id)
    {
        $idArray = array_filter(explode(',', $id), function ($item) {
            return is_numeric($item);
        });
        //查询是否存在单元信息，存在则不允许删除
        return $floorModel->destroy($idArray) ? $this->success('删除成功!') : $this->error('删除失败!');
    }


}
